package com.zhentao.common.admin.utils;

import com.alibaba.fastjson.JSON;
import com.zhentao.common.admin.enums.AdminPermsEnum;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

import static com.zhentao.common.admin.rbac.SysAdminCommon.SYS_PERMISSION_LIST_CACHE_KEY;
import static com.zhentao.common.admin.rbac.SysAdminCommon.SYS_USER_LOGIN_CACHE_KEY_ID;

/**
 * @ClassName: AdminUserPermissionUtils
 * @Author: 振涛教育_Q
 * @Date: 2024/12/27 11:41
 */
@Component
public class AdminUserPermissionUtils {
    private final StringRedisTemplate redisTemplate;

    public AdminUserPermissionUtils(StringRedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    public ResponseResult hasPermission(AdminPermsEnum perms) {
        boolean contains = false;
        // 做权限判断
        // 获取用户id  从缓存中
        String userId = redisTemplate.opsForValue().get(SYS_USER_LOGIN_CACHE_KEY_ID);
        if(StringUtils
                .isEmpty(userId)){
            return ResponseResult.errorResult(AppHttpCodeEnum.CHARGE_USER_DATA_NOT_EXIST);
        }
        // 从缓存中获取权限字符串
        String permsJSON = redisTemplate.opsForValue().get(SYS_PERMISSION_LIST_CACHE_KEY + userId);
        if(StringUtils.isEmpty(permsJSON)){
            return ResponseResult.errorResult(501,"cache select dto exception");
        }
        // 或权限集合
        List<String> permsList = JSON.parseArray(permsJSON, String.class);
        // 从数据库中查询
        if(permsList != null && permsList.size() > 0){
            if (permsList.contains(perms.perms)) {
                contains = true;
            }
        }
        return contains ? ResponseResult.okResult(200000,"权限通过") :
                ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
    }
}
